import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzSafeAny, OnChangeType } from 'ng-zorro-antd/core/types';
import { Observable } from 'rxjs';

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'widget-entity-select',
  template: `
    <nz-select
      [(ngModel)]="selectValue"
      (ngModelChange)="ngModelChange($event)"
      [nzPlaceHolder]="placeholder"
      [nzDisabled]="nzDisabled"
    >
      <nz-option
        *ngFor="let entity of entitys"
        [nzValue]="entity[idKey]"
        [nzLabel]="entity[labelKey]"
      ></nz-option>
    </nz-select>
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => EntitySelectComponent),
      multi: true,
    },
  ],
})
export class EntitySelectComponent implements ControlValueAccessor {
  entitys;
  selectValue;
  onChange: OnChangeType = () => {};
  @Input()
  set getList(fn: () => Observable<NzSafeAny[]>) {
    fn().subscribe(result => {
      this.entitys = result;
    });
  }
  @Input()
  idKey: string = 'id';
  @Input()
  labelKey: string = 'name';
  @Input()
  placeholder: string = '';
  @Input()
  nzDisabled: boolean = false;

  @Output() readonly selectedValueChanged = new EventEmitter();

  constructor() {}
  writeValue(obj: any): void {
    this.selectValue = obj;
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {}
  setDisabledState?(isDisabled: boolean): void {}

  ngModelChange(value) {
    this.onChange(value);
    var entity = this.entitys.find(x => x[this.idKey] == value);
    this.selectedValueChanged.emit(entity);
  }
}
